package util.loaders;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Reads resources from files on the operating system.
 * 
 * @author Jason
 *
 */
public class FileLoader extends DataLoader{

	protected final String rootPath;
	
	/**
	 * If you specify the root as-- <br>
	 *  C:/Users/Bruce/Java/game/images
	 *  <br> <br>
	 * and you wanted to load a file at: <br>
	 *   C:/Users/Bruce/Java/game/images/gui/button.png
	 * 
	 *   you would specify "gui/button.png" as the dataName
	 * @param root
	 */
	public FileLoader(File root){
		if(root.isDirectory() == false)
			throw new RuntimeException("You must specify a valid directory.");
		String path = root.getPath();
		if(path.endsWith(File.separatorChar+"") == false)
			path += File.separatorChar;
		rootPath = path;
	}
	
	@Override
	public InputStream load(String dataName) throws IOException {
		if(dataName == null || dataName.length() < 1)
			throw new RuntimeException("Invalid data name.");
		if(dataName.charAt(0) == File.separatorChar)
			dataName = dataName.substring(1);
		String fullPath = rootPath + dataName;
		File file = new File(fullPath);
		if(file.isFile() == false){
			throw new RuntimeException("Invalid file path: "+fullPath);
		}
		InputStream is = new FileInputStream(file);
		return is;
	}

}
